package net.sudot.chess.business.service;

import net.sudot.chess.business.dao.SocialUserDao;
import net.sudot.chess.business.model.Customer;
import net.sudot.chess.business.model.SocialUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 社会化用户
 *
 * @author tangjialin on 2018-03-15.
 */
@Service
public class SocialUserService extends BaseService<SocialUser> {

    @Resource
    private SocialUserDao socialUserDao;
    @Resource
    private CustomerService customerService;

    /**
     * 获取社会化用户
     *
     * @param loginPluginId 登录插件ID
     * @param uniqueId      唯一ID
     * @return 社会化用户，若不存在则返回null
     */
    public SocialUser findByUniqueId(String loginPluginId, String uniqueId) {
        return socialUserDao.findByUniqueId(loginPluginId, uniqueId);
    }

    /**
     * 获取社会化用户
     *
     * @param loginPluginId 登录插件ID
     * @param userId        用户主键
     * @return 社会化用户，若不存在则返回null
     */
    public SocialUser findByUser(String loginPluginId, Long userId) {
        return socialUserDao.findByUser(loginPluginId, userId);
    }

    /**
     * 保存用户信息
     *
     * @param socialUser 社会化用户信息
     * @param inviter    邀请者
     * @return 返回保存后的社会化用户信息
     */
    @Transactional(rollbackFor = Exception.class)
    public SocialUser save(SocialUser socialUser, Long inviter) {
        Customer customer = customerService.register(new Customer(), inviter);
        socialUser.setUserId(customer.getId());
        return super.save(socialUser);
    }
}
